<?php
/**
 * Created by PhpStorm.
 * User: dayu
 * Date: 2019/12/16
 * Time: 10:44
 */

namespace app\Validate;

use \think\Validate;
use \think\Request;
use think\Loader;
use think\exception\ValidateException;

class RequestValidate extends Validate
{
    //当前请求的方法名
    protected $action;
    public $request;

    public function __construct()
    {
        $this->request = Request::instance();
        $this->action = $this->request->action();
        switch (strtolower($_SERVER['REQUEST_METHOD'])) {
            case 'get':
                $data = $this->request->get();
                break;
            case 'post':
                $data = $this->request->post();
                break;
            case 'param':
                $data = $this->request->param();
                break;
            case 'put':
                $data = $this->request->put();
                break;
            case 'request':
                $data = $this->request->request();
                break;
        }
        $rules = $this->rulesList();
        $this->sometimes($rules, $data);
        $result = $this->validate($data, $rules, $this->messagesList());
        if (true !== $result) {
            exit( json_encode(return_json_data($result, 500)));
        }
    }

    //自定义验证方式
    protected function sometimes(&$rules, $data)
    {
        foreach ($rules as $k => $v) {
            if (array_key_exists($k, $data)) {
                if (substr($v, 0, 10) == 'sometimes|'){
                    $rules[$k] = str_replace("sometimes|", '', $v);
                }
            } else {
                if (substr($v, 0, 10) == 'sometimes|'){
                    unset($rules[$k]);
                }
            }
        }
    }

    protected function rulesList()
    {
        return [
            //
        ];
    }

    protected function messagesList()
    {
        return [
            //
        ];
    }

    protected function validate($data, $rules, $message = [], $batch = true, $failException = false, $callback = null)
    {
        if (is_array($rules)) {
            $v = Loader::validate();
            $v->rule($rules);
        } else {
            if (strpos($rules, '.')) {
                // 支持场景
                list($rules, $scene) = explode('.', $rules);
            }
            $v = Loader::validate($rules);
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        // 是否批量验证
        if ($batch) {
            $v->batch(true);
        }
        if (is_array($message)) {
            $v->message($message);
        }
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }
        if (!$v->check($data)) {
            if ($failException) {
                throw new ValidateException($v->getError());
            } else {
                return $v->getError();
            }
        } else {
            return true;
        }
    }

}